<?php

namespace App\Console\Commands;

use App\Http\Models\Mysql\SsyAllocationIpurchaseListTable;
use App\Http\Models\Mysql\SsyAllocationOrderListTable;
use App\Http\Models\Mysql\SsyAllocationOrderReturnTable;
use App\Http\Models\Mysql\SsyAllocationOrderTable;
use App\Http\Models\Mysql\SsyAllocationSaleListTable;
use App\Http\Models\Mysql\SsyAllocationSaleTable;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class updateAllocationStatus extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:updateAllocationStatus {--allocation_number=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新调拨计划单的归还状态';

    /**
     * Create a new command instance.
     * 0 /1 * * *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $autoKey = "auto_updateAllocationReturnStatus";
        Cache::put($autoKey, 1, Carbon::now()->addMinutes(15));
        $conn = (new SsyAllocationOrderListTable())->whereIn('data_return', [0, 1])->where('status', 1)->where('data_status', 0);
        $allocationNumbers = $this->option("allocation_number") ?? "";
        if(!empty($allocationNumbers)){
            $allocationNumbers = explode(',', $allocationNumbers);
            $conn = $conn->whereIn('allocation_number', $allocationNumbers);
        }
        $allocationList = $conn->get(['id','groups', 'allocation_number'])->toArray();
        $total = count($allocationList);
        $num = 1;
        foreach($allocationList as $allocationObj){
            $groups = $allocationObj['groups'];
            $allocationNumber = $allocationObj['allocation_number'];
            echo "共[$total, $num]条, 正在执行: $allocationNumber \n";
            $num++;
            if($groups == 3){//还
                $this->setH($allocationNumber, $allocationObj['id']);
            }
            if(in_array($groups, [2, 4])){//借
                $this->setJ($allocationNumber, $allocationObj['id']);
            }
            if($groups == 1){//赠
                $this->setZ($allocationNumber, $allocationObj['id']);
            }
        }
        Cache::forget($autoKey);
    }

    //处理 借出调拨
    public function setJ($allocationNumber, $allocationId)
    {
        $actuallyNum = 0;//实际调拨数
        $actuallyReturnNum = 0;//实际归还数
        $giveNum = 0;//转赠送数
        $ipurchaseNum = 0;//转内购数
        $saleNum = 0;//借转销售

        //实际调拨数
        $actuallyNum = (Int)((new SsyAllocationOrderReturnTable())->where('allocation_number', $allocationNumber)->where('transfer_type', 1)->sum('sj_num'));
        //实际归还数
        $actuallyReturnSkuMap = [];
        $allocationReturnList = (new SsyAllocationOrderListTable())->where('source_allocation_number', $allocationNumber)->where('status', 1)->where('groups', 3)
            ->get(['allocation_number'])->toArray();
        if(!empty($allocationReturnList)){
            $allocationNums = array_column($allocationReturnList, 'allocation_number');
            $actuallyReturnList = (new SsyAllocationOrderReturnTable())->whereIn('allocation_number', $allocationNums)->where('transfer_type', 1)
                ->get(['sku_code', 'sj_num'])->toArray();
            foreach ($actuallyReturnList as $item){
                $actuallyReturnNum += $item['sj_num'];
                $actuallyReturnSkuMap[$item['sku_code']] = ($actuallyReturnSkuMap[$item['sku_code']] ?? 0) + $item['sj_num'];
            }
        }
        //转赠送数
        $allocationGiveList = (new SsyAllocationOrderListTable())->where('source_allocation_number', $allocationNumber)->where('status', 1)->where('groups', 1)
            ->get(['allocation_number'])->toArray();
        if(!empty($allocationGiveList)){
            $allocationNums = array_column($allocationGiveList, 'allocation_number');
            $giveNum = (new SsyAllocationOrderTable())->whereIn('allocation_number', $allocationNums)->sum('num');
        }
        //转内购数
        $ipurchaseObj = (new SsyAllocationIpurchaseListTable())->where('jc_number', $allocationNumber)->where('status', 1)->first(['total_num']);
        $ipurchaseNum = $ipurchaseObj->total_num ?? 0;
        //借转销售
        $saleOrders = (new SsyAllocationSaleTable())->where('source_allocation_number', $allocationNumber)
            ->get(['allocation_number','source_allocation_number', 'num'])->toArray();
        $allocationSaleNums = array_column($saleOrders, 'allocation_number');
        if(!empty($allocationSaleNums)){
            $saleList = (new SsyAllocationSaleListTable())->whereIn('allocation_number', $allocationSaleNums)->where('status', 1)->get(["allocation_number"])->toArray();
            $allocationSaleValidNums = array_column($saleList, 'allocation_number');
            foreach ($saleOrders as $item){
                if(in_array($item['allocation_number'], $allocationSaleValidNums)){
                    $saleNum += $item['num'];
                }
            }
        }
        $totalReturnNum = (Int)$actuallyReturnNum + (Int)$giveNum + (Int)$ipurchaseNum + (Int)$saleNum;
        if($totalReturnNum == 0){
            echo "当前借出调拨计划，未归还, 未转赠送, 未转内购, 未转销售\n";
            return ['code' => -1, 'msg' => '当前调拨计划未归还'];
        }
        $dataReturn  = $actuallyNum <= $totalReturnNum ? 2 : 1;
        $allocationOrders = (new SsyAllocationOrderTable())->where('allocation_number', $allocationNumber)->get(['id', 'sku_code', 'is_return', 'num'])->toArray();
        foreach ($allocationOrders as $item){
            $returnNum = $actuallyReturnSkuMap[$item['sku_code']] ?? 0;
            if($returnNum == 0 || $item['is_return'] == 2){
                continue;
            }
            (new SsyAllocationOrderTable())->updateData($item['id'], ['is_return' => $item['num'] <= $returnNum ? 2 : 1]);
        }
        return (new SsyAllocationOrderListTable())->updateData($allocationId, ['data_return' => $dataReturn]);
    }

    //处理 赠送调拨
    public function setZ($allocationNumber, $allocationId)
    {
        $actuallyGiveNum = 0;//实际赠送数
        $actuallyReturnNum = 0;//实际归还数
        $giveList = (new SsyAllocationOrderReturnTable())->where('allocation_number', $allocationNumber)->where('transfer_type', 1)
            ->get(['sku_code', 'sj_num'])->toArray();
        $actuallySkuMap = [];
        foreach($giveList as $item){
            $actuallyGiveNum += $item['sj_num'];
            $actuallySkuMap[$item['sku_code']] = ($actuallySkuMap[$item['sku_code']] ?? 0) + $item['sj_num'];
        }
        $allocationReturnList = (new SsyAllocationOrderListTable())->where('source_allocation_number', $allocationNumber)->where('status', 1)->where('groups', 3)
            ->get(['allocation_number'])->toArray();
        $actuallyReturnSkuMap = [];
        if(!empty($allocationReturnList)){
            $allocationNums = array_column($allocationReturnList, 'allocation_number');
            $actuallyReturnList = (new SsyAllocationOrderReturnTable())->whereIn('allocation_number', $allocationNums)->where('transfer_type', 1)
                ->get(['sku_code', 'sj_num'])->toArray();
            foreach ($actuallyReturnList as $item){
                $actuallyReturnNum += $item['sj_num'];
                $actuallyReturnSkuMap[$item['sku_code']] = ($actuallyReturnSkuMap[$item['sku_code']] ?? 0) + $item['sj_num'];
            }
        }
        if($actuallyReturnNum == 0){
            echo "当前赠送调拨计划，未转归还\n";
            return ['code' => -1, 'msg' => '当前调拨计划未归还'];
        }
        $dataReturn  = $actuallyGiveNum <= $actuallyReturnNum ? 2 : 1;
        $allocationOrders = (new SsyAllocationOrderTable())->where('allocation_number', $allocationNumber)->get(['id', 'sku_code', 'is_return', 'num'])->toArray();
        foreach ($allocationOrders as $item){
            $returnNum = $actuallyReturnSkuMap[$item['sku_code']] ?? 0;
            if($returnNum == 0 || $item['is_return'] == 2){
                continue;
            }
            (new SsyAllocationOrderTable())->updateData($item['id'], ['is_return' => $item['num'] <= $returnNum ? 2 : 1]);
        }
        return (new SsyAllocationOrderListTable())->updateData($allocationId, ['data_return' => $dataReturn]);
    }

    //处理 归还调拨
    public function setH($allocationNumber, $allocationId)
    {
        $planNum = 0;//计划归还数
        $actuallyNum = 0;//实际归还数
        $returnList = (new SsyAllocationOrderReturnTable())->where('allocation_number', $allocationNumber)->where('transfer_type', 1)
            ->get(['sku_code', 'sj_num'])->toArray();
        $actuallySkuMap = [];
        foreach ($returnList as $item){
            $actuallyNum += $item['sj_num'];
            $actuallySkuMap[$item['sku_code']] = ($actuallySkuMap[$item['sku_code']] ?? 0) + $item['sj_num'];
        }
        if($actuallyNum == 0){
            echo "当前归还调拨计划，未实际归还\n";
            return ['code' => -1, 'msg' => '当前调拨计划未归还'];
        }
        $allocationOrders = (new SsyAllocationOrderTable())->where('allocation_number', $allocationNumber)->get(['id', 'sku_code', 'is_return', 'num'])->toArray();
        foreach ($allocationOrders as $item){
            $planNum += $item['num'];
            $returnNum = $actuallySkuMap[$item['sku_code']] ?? 0;
            if($returnNum == 0 || $item['is_return'] == 2){
                continue;
            }
            (new SsyAllocationOrderTable())->updateData($item['id'], ['is_return' => $item['num'] <= $returnNum ? 2 : 1]);
        }
        return (new SsyAllocationOrderListTable())->updateData($allocationId, ['data_return' => $planNum <= $actuallyNum ? 2 : 1]);
    }
}
